package com.zeng.stpro.commons.utils;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.compression.GzipCompressionCodec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

import java.util.Date;

/**
 * @Author ZENGZHIJUN
 * @Date 2021/2/4 14:30
 *
 * JWT 工具类
 */
public class JwtUtils {

    private static Logger logger = LoggerFactory.getLogger(JwtUtils.class);

    private static long tokenExpiration = 24*60*60*1000; //ms
    private static String tokenSingKey = "ZENGZHIJUN";

    /**
     * 生成 JWT 口令
     * @param username
     * @return
     */
    public static String createToken(String username) {
        return Jwts.builder()
                .setSubject(Base64Utils.encodeToString(username.getBytes()))
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .signWith(SignatureAlgorithm.HS512, tokenSingKey)
                .compressWith(new GzipCompressionCodec()).compact();
    }

    /**
     * 解析 JWT 口令
     * @param token
     * @return
     */
    public static Claims obtainClaims(String token) {
        return Jwts.parser().setSigningKey(tokenSingKey).parseClaimsJws(token).getBody();
    }

    /**
     * 解析 token
     * @param token
     * @return
     */
    public static String parseToken(String token) {
        String info = Jwts.parser().setSigningKey(tokenSingKey).parseClaimsJws(token).getBody().getSubject();
        return new String(Base64Utils.decodeFromString(info));
    }

    /**
     * 判断 token 是否过期
     * @param token
     * @return
     */
    public static boolean isExpired(String token) {
        return Jwts.parser().setSigningKey(tokenSingKey).parseClaimsJws(token).getBody().getExpiration().before(new Date());
    }


    public static void main(String[] args) {
        System.out.println(JwtUtils.createToken("admin"));
        //eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJSigwPKkkMN7FV0lFKrShQsjI0MzQyNTC3MDStBQCOGkvyIwAAAA.JaNTTk7DaG2MlqhbN1KpvvG4a6m0FauOENWP_O5n8wHi5XKlC1UJWMrdvC_CABINnIW_ukcH50sB9jujhZU0fA
        System.out.println(JwtUtils.parseToken("eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJSigwPKkkMN7FV0lFKrShQsjI0MzQyNTC3MDStBQCOGkvyIwAAAA.JaNTTk7DaG2MlqhbN1KpvvG4a6m0FauOENWP_O5n8wHi5XKlC1UJWMrdvC_CABINnIW_ukcH50sB9jujhZU0fA"));
    }


    public static void removeToken(String token) {
        System.out.println("移除 token 成功");
    }
}
